package com.luo.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {
    //jdbc->Connection
    //mybatis->SqlSession<-SqlSessionFactory:读取mybatis-config.xml文件香瓜的数据库、映射文件等
    //形成一个映像(配置对象)放于内存中
    //SqlSessionFactoryBuilder->SqlSessionFactory

    //3.声明一个SqlSessionFactory(最好一份 并且单例)
    private static SqlSessionFactory sqlSessionFactory = null;

    public static SqlSession getSqlSession() {
        if (sqlSessionFactory == null) {
            //3.1获取配置文件的输入流
            try {
                InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory.openSession();
    }
}